package at.jku.ase.communication.parsers;

import at.jku.ase.communication.SessionObject;
import at.jku.ase.utils.ObjectUtils;

import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import java.security.PublicKey;

/**
 * This class parses the the public key from receiver, and set it to session object
 */
public class PublicKeyParser extends ComponentParser<PublicKey> {

    public PublicKeyParser(SessionObject sessionObject, XMLResponse action) {
        super(sessionObject, action);
    }

    public PublicKey processRequest(XMLStreamReader reader) throws XMLStreamException {
        String clientId = reader.getAttributeValue(0);
        this.getSession().setId(clientId);
        if (reader.next() == XMLStreamConstants.CHARACTERS) {
            System.out.println("Parsing public key object");
            String base64Text= reader.getText();
            PublicKey publicKey = ObjectUtils.convert(base64Text);
            System.out.println("Set receiver public key to session object");
            this.getSession().setReceiverPublicKey(publicKey);
        }
        return this.getSession().getReceiverPublicKey();
    }

}
